<template>
  <div class="goods-box">
    <nav-header></nav-header>
    <nav-bread>
      <span class="bread-item">My Cart</span>
    </nav-bread>
    <div class="cart-list">
      <h1 class="cart-title">M Y&nbsp&nbsp&nbsp&nbspC A R T</h1>
      <el-table
        :data="cartList"
        ref="table"
        style="width: 100%"
        :header-cell-style="{background:'#605f5f',color:'#fff',size:'20px'}"
        @select="handleSelect" 
        @select-all="handleSelectAll"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          min-width="5%">
        </el-table-column>
        <el-table-column
          prop="productImage"
          label="ITEMS"
          min-width="20%"
        >
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="`/static/image/${scope.row.productImage}`"
          >
          </el-image>
        </template>
        </el-table-column>
        <el-table-column
          prop="productName"
          label=""
          min-width="10%">
        </el-table-column>
        <el-table-column
          prop="salePrice"
          label="PRICE"
          min-width="20%">
          <template slot-scope="scope">
            <span class="price">{{scope.row.salePrice | currency('￥')}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="productNum" 
          label="QUANTITY"
          min-width="20%">
          <template slot-scope="scope">
            <el-input-number :min="0" size="small" v-model="scope.row.productNum" @change="numChange(scope.row.productNum,scope.row.productId,scope.row.checked)"></el-input-number>
          </template> 
        </el-table-column>
        <el-table-column
          prop="sub"
          label="SUBTOTAL"
          min-width="25%">
          <template slot-scope="scope">
            <span class="price">{{scope.row.productNum*scope.row.salePrice | currency('￥')}}</span>
          </template> 
        </el-table-column>
        <el-table-column
          label="EDIT"
          min-width="10%">
          <template slot-scope="scope">
            <el-button @click="handleDeleteClick(scope.row)" type="danger" icon="el-icon-delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="cart-pay">
        <div class="pay-price">总金额: {{subPrice | currency('￥')}}</div>
        <!-- <div class="pay-btn not-active">CHECKOUT</div> -->
        <el-button type="info" class="pay-btn" @click="handleCheckout">CHECKOUT</el-button>
      </div>
    </div>
    <nav-footer></nav-footer>
  </div>
</template>
<script>
import NavHeader from '@/components/Header'
import NavFooter from '@/components/Footer' 
import NavBread from '@/components/Bread'

export default {
  name: 'CartList',
  
  components: {
    NavHeader,
    NavFooter,
    NavBread
  },
  data () {
    return {
      num: 1,
      subPrice: '',
      cartList: [],
      isChecked: 0
    }
  },
  watch: {
    cartList () {
      // console.log(1111111111111111)
    }
  },
  methods: {
    cartListInit () {
      // console.log('==='+this.isChecked)
      this.$axios.get('/api/users/cartList').then((response) => {
        let res = response.data
        this.cartList = res.result
        var sum = ''
        // vm.$nextTick([callback])
        //将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它，然后等待 DOM 更新。
        // 不加没效果
        // console.log(this.cartList)
        this.$nextTick(()=>{
          for(let i = 0; i < this.cartList.length; i++){
            if(this.cartList[i].checked == '1') {
            this.$refs.table.toggleRowSelection(this.cartList[i],true)
            // sum += parseFloat(this.cartList[i].salePrice) * parseInt(this.cartList[i].productNum) 
            this.isChecked = 1
            } else {
              this.$refs.table.toggleRowSelection(this.cartList[i],false)
              this.isChecked = 0
            }
          }
        })
        
      })
      console.log('11==='+this.isChecked)
    },
    handleDeleteClick (row) {
      this.$confirm("确认删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$axios.post('/api/users/del',{productId:row.productId}).then((res) => {
          var data = res.data
          if(data.status == '0') {
            this.cartListInit()
            this.$message({
              type: "success",
              message: "删除成功!"
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        })
      }) 
    },
    numChange (num,id,isChecked) {
      // console.log('numChange')
      // console.log('后1===='+this.isChecked)
      // console.log('后2===='+isChecked)      
      this.$axios.post('/api/users/cartChange', {
        productId: id,
        productNum: num,
        checked: isChecked
      }).then((res) => {
        let data = res.data
        if(data.status == '0') {
          console.log('succ')
          this.cartListInit()
        } else {
          console.log('fail')
        }
      })
    },
    // 选择所有选中的数据 (全选)
    handleSelectAll (val) {
      // console.log(val.length)
      // this.$refs.cartList.setCurrentRow(val)
      if(val.length !== 0) {
        var checkAll = true
      } else {
        checkAll = false
      }
      this.$axios.post('/api/users/editCheckAll',{
          checkAll:checkAll
        }).then((res)=>{
          let data = res.data
          if(data.status == '0') {
            console.log('success')
          } else {
            console.log('fail');
          }
        })
      
    },
    // 选择单行数据 (单选)
    handleSelect (val,row) {
      // console.log("handleSelect")
      let selected = val.length && val.indexOf(row) !== -1 // true就是选中，0或者false是取消选中
      // console.log(selected)
      let id = row.productId,
          num = row.productNum
      // console.log(selected)
      // 未选中， 点击后选中 ===>  selected == true
      if(selected == true) {
        this.isChecked = 1
        // console.log('前'+this.isChecked)
        this.numChange(num,id,this.isChecked)
      } else {
        this.isChecked = 0
        this.numChange(num,id,this.isChecked)
      }
    },
    handleSelectionChange(val) {
      // console.log(val)
      var sum = 0
      val.forEach((item)=>{
        sum += parseFloat(item.salePrice) * parseInt(item.productNum)
      })
      this.subPrice = sum
      console.log(val.length)
    },
    // 结算
    handleCheckout () {

      if(this.subPrice == 0) {
        this.$message({
          message: '您还未勾选任何商品哦！',
          type: 'warning'
        })
      } else {
        this.$router.push('/address')
      }
    }
  },
  mounted() {
    this.cartListInit() 
    console.log('mounted'+this.isChecked)
  },
  // beforeDestroy () {
  //   console.log(111111)
  //   this.isChecked = 0
  // }
  // beforeUpdate(){
  //   console.log('beforeU'+this.isChecked)
  // },
  updated() {
    // console.log('updated'+this.isChecked)this
    // this.cartListInit()
  },
}
</script>

<style lang="stylus" scoped>
  .goods-box
    background #f5f7fc
    font-size 14px
    .bread-item
      color #409eff
    .cart-list
      width 1260px
      margin 0 auto
      background #f5f7fc
      .cart-title
        font-size 22px
        margin 30px 0
  .goods-box >>> .el-table th>.cell
    text-align: center;
    font-size: 15px;
    font-weight: bold;
  .goods-box >>> .el-table td
    text-align center
    height 150px
    padding 0
    font-size 15px
  .cart-pay
    height 55px
    margin 20px 0
    background #fff
    border 1px solid #ccc
    .pay-btn
      width 150px
      float right
      background #d1434a
      font-weight bold
      font-size 16px
      height 55px
      border none
    .pay-btn:hover
      background #f16f75
      transition all .3s ease-out
    .pay-price
      width 200px
      float left
      text-align left
      padding-left 10px
      font-weight bold
      font-size 16px
      height 55px
      line-height 53px
      color #d1434a
  .price
    color red
    font-weight bold
</style>
